package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"pro/global"
	"pro/internal/models"
	"pro/internal/params"
	"pro/pkg/baidu_text_review"
	"pro/pkg/rabbitmq"
)

type VideoHandler struct {
	review   *baidu_text_review.Review
	rabbitmq *rabbitmq.RabbitMQ
}

func NewHandler() *VideoHandler {
	rmq := rabbitmq.NewRabbitMQSimple("review_log")
	return &VideoHandler{
		review:   baidu_text_review.NewReview(),
		rabbitmq: rmq,
	}
}

func AddVideo(c *gin.Context) {
	var err error
	var req params.AddVideoReq
	var v models.Videos

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	VideoCensor := NewHandler().review
	if !VideoCensor.TestingStringV2(req.Title, req.Url) {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "视频内容不合规",
		})
		return
	}

	global.DB.Model(&v).Update("status", 2)

	v.Title = req.Title
	v.Author = req.Author
	v.Tags = req.Tag
	v.Url = req.Url

	if err = v.AddVideo(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "视频发布失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "视频审核通过",
		"videoId": v.ID,
	})
}

func VideoInfo(c *gin.Context) {
	var err error
	var req params.VideoInfo
	var v models.Videos

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = v.GetVideoInfoById(req.Id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    400,
			"message": "视频信息获取失败",
		})
		return
	}
	if v.ID == 0 {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "该视频不存在",
		})
		return
	}

	if err = global.DB.Model(&v).Where("id=?", req.Id).
		UpdateColumn("visit", gorm.Expr("visit + ?", 1)).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    400,
			"message": "览量次数增加失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "查看视频详情成功",
		"videoId": v,
	})

}
